const chokidar = require('chokidar');  
const WebSocket = require('ws');  
const fs = require('fs');
const sharp = require('sharp');  
const { createCanvas, loadImage } = require('canvas');  
const { spawn } = require("child_process");
const { error } = require('console');

// WebSocket 服务器配置  
const wss = new WebSocket.Server({ port: 7002 });  

const imagesDir = '/work/output/'; 
if (!fs.existsSync(imagesDir)) {
  fs.mkdirSync(imagesDir);
} 
// 监听文件夹  
const watcher = chokidar.watch(imagesDir, {  
  persistent: true,  
  depth: 99,  
  ignoreInitial: false,  
});  
  
// 发送消息到所有连接的 WebSocket 客户端  
function broadcast(message) {  
  wss.clients.forEach(client => {  
    if (client.readyState === WebSocket.OPEN) {  
      client.send(message, { binary: true });
    }  
  });  
}

function startImage(rtspUrl, outputFolder) {
  // 执行FFmpeg命令每秒切图
  const ffmpegProcess = spawn("ffmpeg", [
    "-rtsp_transport", "tcp", "-i", rtspUrl, "-vf", "fps=25", `${outputFolder}image%d.jpg`,
  ]);
  ffmpegProcess.stdout.on("data", (data) => {
    console.log(`stdout: ${data}`);
  });

  ffmpegProcess.stderr.on("data", (data) => {
    console.error(`stderr: ${data}`);
  });

  ffmpegProcess.on("close", (code) => {
    console.log(`FFmpeg process exited with code ${code}`);
  });
  return ffmpegProcess;
}
  
// 监听文件夹变化事件  
watcher  
  .on('add', async path => {  
    fs.readFile(path, async function(err, data) {
      if (err) {
        console.error(err);
        return;
      }
      broadcast(data); 
      try {
        fs.unlink(path, (err) => {
          if (err) throw err;
        }); 
      } catch (err) {
        console.log(err);
      }
    });
  })
  
// WebSocket 服务器事件处理  
wss.on('connection', ws => {  
  ws.on('message', message => {  
    console.log('received: %s', message);  
  });  
  ws.on('close', () => {  
    console.log('client disconnected');  
  });  
});  
console.log('WebSocket server listening on port 7002');

startImage('rtsp://admin:broadnet123@192.168.100.109:554/Streaming/Channels/1', imagesDir)

let index = 1;
setInterval(function() {  
  wss.clients.forEach(client => {  
    if (client.readyState === WebSocket.OPEN) {  
      const message = "hello world - " + index++;
      client.send(message);
    }  
  });
}, 1000);